package com.bml.architect.seata.service.impl;

import com.bml.architect.seata.entity.Storage;
import com.bml.architect.seata.mapper.StorageMapper;
import com.bml.architect.seata.service.StorageService;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: baiml
 * @Title: StorageServiceImpl
 * @ProjectName: 中台技术平台
 * @Depart 中台研发部
 * @Description:
 * @date: 2021/5/12 9:04
 */
@Service
public class StorageServiceImpl implements StorageService {
    @Autowired
    private StorageMapper storageMapper;

    private Logger logger = LoggerFactory.getLogger(StorageServiceImpl.class);


    @Transactional
    @Override
    public Boolean deduct(String commodityCode, int count) {
        logger.info("++++++++++++++++++++扣减库存");

        logger.info("当前 XID: {}", RootContext.getXID());
        checkStorage(commodityCode, count);
        logger.info("开始扣减 {} 库存", commodityCode);
        Integer record = storageMapper.reduceStorage(commodityCode, count);
        logger.info("扣减 {} 库存结果:{}", commodityCode, record > 0 ? "操作成功" : "扣减库存失败");
        return true;
    }


    private void checkStorage(String commodityCode, int count) {
        Storage byCommodityCode = storageMapper.findByCommodityCode(commodityCode);
        if (byCommodityCode == null) {
            throw new RuntimeException("商品编号为 " + commodityCode + "的库存为空");
        }
        Integer kc = byCommodityCode.getCount();
        if (kc - count < 0) {
            logger.warn("{} 库存不足，当前库存:{}", commodityCode, count);
            throw new RuntimeException("库存不足");
        }
    }
}
